import React, { useEffect, useRef } from "react";
import styled from "styled-components";
import Card from "@mui/material/Card";
import * as echarts from "echarts";
import { setBarChartOpt } from "./barChartOpt";
import { connect } from "react-redux";
import { parseToRecordWeek } from "redux/reducers/recordList";
const StatisticWrapper = styled.div`
  .chart {
    height: 200px;
  }
`;

const WeekChartList = (props: any) => {
  const initChart = (
    divRef: HTMLElement,
    data: barDataType[],
    title: string
  ) => {
    const _chart = echarts.init(divRef);
    const _opt = setBarChartOpt(data, title);
    _opt && _chart.setOption(_opt);
  };
  let outbarData: barDataType[] = [];
  let inbarData: barDataType[] = [];
  const initData = (records: RecordType[], type: number) => {
    const weekRecords = parseToRecordWeek(records);
  
    const barData: barDataType[] = [];
    weekRecords.children.map((value) => {
      barData.push({
        key: value.weekOfDay,
        value: type === 0 ? value.output : value.input,
      });
    });
    return barData;
  };
  const records = props.records;
  const inputRef = useRef(null);
  const outputRef = useRef(null);
  outbarData = initData(records, 0);
  inbarData = initData(records, 1);
  useEffect(() => {
      initChart(outputRef.current!, outbarData, "本周支出");
      initChart(inputRef.current!, inbarData, "本周收入");
  });
  return (
    <StatisticWrapper>
      <Card sx={{ margin: "10px 10px",padding: "8px" }}>
        <div ref={outputRef} className="chart"></div>
      </Card>
      <Card sx={{ margin: "10px 10px" ,padding: "8px"}}>
        <div ref={inputRef} className="chart"></div>
      </Card>
    </StatisticWrapper>
  );
};
const mapStateToProps = (state: any) => {
  return { records: state.record };
};
export default connect(mapStateToProps)(WeekChartList);
